package com.lottery.controller;

import com.lottery.dto.SimpleOutputDTO;
import com.lottery.pojo.User;
import com.lottery.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("getUsers")
    public List<User> getUsers() {
        return userService.getUsers();
    }

    /**
     * 登录
     * [username+password]http://localhost:8001/login?username=admin&password=$2y$10$rV69RAsAFDPyPJA19Lc43OPXHQ17mn4yrt2v0XQ9ZUwq.p8Jv3k2.
     */
    @PostMapping("login")
    public SimpleOutputDTO<Boolean> login(String username, String password) {
        SimpleOutputDTO<Boolean> outputDTO = new SimpleOutputDTO<>();
        int login = userService.login(username, password);
        if (login > 0) {
            outputDTO.setCode(0);
            outputDTO.setMessage("success");
            outputDTO.setData(true);
        } else {
            outputDTO.setCode(-1);
            outputDTO.setMessage("帐号或密码错误！");
            outputDTO.setData(false);
        }
        return outputDTO;
    }

    /**
     * 修改密码
     */
    @PostMapping("resetPassword")
    public SimpleOutputDTO<Boolean> resetPassword(String username, String oldPassword, String newPassword) {
        log.info("resetPassword(), username:" + username + ", oldP:" + oldPassword + ", newP:" + newPassword);
        SimpleOutputDTO<Boolean> outputDTO = new SimpleOutputDTO<>();
        User user = userService.getUser(username);
        if (user == null || user.getUsername().equals("") || !user.getPassword().equals(oldPassword)) {
            outputDTO.setCode(-1);
            outputDTO.setMessage("旧密码验证错误！");
        }

        userService.resetPassword(username, oldPassword, newPassword);
        return outputDTO;
    }


    //------------------app
    /*登录machines*/
    @PostMapping("appLogin")
    public SimpleOutputDTO<Boolean> appLogin(String machine_number, String password) {
        log.info("appLogin(), machine_number:{}, password:{}", machine_number, password);
        SimpleOutputDTO<Boolean> outputDTO = new SimpleOutputDTO<>();
        int login = userService.appLogin(machine_number, password);
        outputDTO.setData(login > 0);
        return outputDTO;
    }
}
